<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入车辆名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="车辆号码" prop="carNumber">
        <el-input
          v-model="queryParams.carNumber"
          placeholder="请输入车辆号码"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="handleView()"
        class="manage-add-btn"
        >添加车辆</el-button
      >
    </el-form>
    <el-table ref="tables" v-loading="loading" :data="list">
      <el-table-column label="车辆编号" align="center" prop="carNumber" />
      <el-table-column label="车辆图片" align="center">
        <template slot-scope="{ row }">
          <el-image
            style="width: 50px; height: 50px"
            :src="formattedHeadIcon(row.imageUrl)"
            fit="fill"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="车辆号码" align="center" prop="licencePlate" />
      <el-table-column label="车辆名称" align="center" prop="name" />
      <el-table-column label="车辆分类" align="center" prop="classifyName" />
      <el-table-column label="是否启用" align="center">
        <template slot-scope="{ row }">
          <div v-if="row.status == 0">正常</div>
          <div v-if="row.status == 1">冻结</div>
          <div v-if="row.status == 2">空闲</div>
          <div v-if="row.status == 3">维修</div>
        </template>
      </el-table-column>
      <el-table-column label="驾驶人" align="center" prop="driverName" />
      <el-table-column label="手机号" align="center" prop="driverPhone" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="摄像头" align="center">
        <template slot-scope="{ row }">
          <el-tag :type="row.isCamera == 1 ? 'success' : 'info'">
            {{ row.isCamera == 1 ? '存在' : '不存在' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row, scope.index)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            style="color: #f56c6c"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 操作日志详细 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        label-width="100px"
        size="mini"
        :rules="rules"
      >
        <el-form-item label="车辆名称：" prop="name" style="width: 60%">
          <el-input
            v-model="form.name"
            type="text"
            placeholder="请输入车辆名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="车辆编号：" prop="carNumber" style="width: 60%">
          <el-input
            v-model="form.carNumber"
            type="tel"
            placeholder="请输入车辆编号"
            maxlength="12"
          ></el-input>
        </el-form-item>
        <el-form-item label="车辆图片：" style="width: 60%">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :headers="headers"
            :show-file-list="false"
            name="image"
            :on-success="handleUploadSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.imageUrl"
              :src="formattedHeadIcon(form.imageUrl)"
              class="uploadimage"
            />
            <el-button v-else type="success">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="车辆分类：" prop="member">
          <el-select
            placeholder="请选择车辆分类"
            v-model="form.classifyName"
            clearable
            filterable
          >
            <el-option
              v-for="(m, index) in classifyList"
              :key="index"
              :label="m.className"
              :value="m.className"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆号码：" style="width: 60%">
          <el-input
            v-model="form.licencePlate"
            type="tel"
            placeholder="请输入车辆号码"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="驾驶人：" style="width: 60%">
          <el-select
            placeholder="请选择车辆分类"
            v-model="form.driverName"
            clearable
            filterable
          >
            <el-option
              v-for="(m, index) in driverlist"
              :key="index"
              :label="m.name"
              :value="m.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号：" style="width: 60%">
          <el-input
            v-model="form.driverPhone"
            type="tel"
            placeholder="请输入手机号"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="车辆状态：" style="width: 60%">
          <el-radio-group v-model="form.status">
            <el-radio-button
              v-for="item in statusList"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio-button
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="摄像头：" style="width: 60%">
          <el-radio-group v-model="form.isCamera">
            <el-radio :label="1">存在</el-radio>
            <el-radio :label="0">不存在</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门：" prop="tap">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  carlist,
  addCar,
  editCar,
  changeStatus,
  carClassifylist,
  delCar,
} from "@/api/system/car";
import { getToken } from "@/utils/auth";
import { deptChildTreeSelect, deptTreeSelect } from "@/api/system/user";
import { list } from "@/api/personnel/manage";
import store from "@/store";
const prefix = process.env.VUE_APP_CDN_HOST;
export default {
  name: "vehice",
  data() {
    return {
      title: "添加车辆",
      editId: null,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileType: {
        type: Array,
        default: () => ["png", "jpg", "jpeg"],
      },
      statusList: [
        { label: "正常", value: "0" },
        { label: "冻结", value: "1" },
        { label: "空闲", value: "2" },
        { label: "维修", value: "3" },
      ],
      rules: {
        name: [{ required: true, message: "请填写车辆名称", trigger: "blur" }],
        carNumber: [
          { required: true, message: "请填写车辆编号", trigger: "blur" },
        ],
      },
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        carNumber: "",
        name: "",
        classify: "",
        classifyName: "",
        licencePlate: "",
        imageUrl: "",
        driverPhone: "",
        deptId: "",
        status: "0",
        driverName: "",
        driverId: "",
        isCamera: 0, // 默认不存在摄像头
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      classifyList: [],
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "deptName",
      },
      driverlist: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formattedHeadIcon(icon) {
      return prefix + icon;
    },
    /** 查询登录日志 */
    getList() {
      this.loading = true;
      carlist(this.queryParams).then((response) => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.pageNum = 1;
    },
    /** 详细按钮操作 */
    async handleView(row) {
      // 先并行加载数据源，再打开弹窗并赋值到表单（使用拷贝切断引用）
      this.getDeptTree();
      // 并行请求分类和驾驶人列表，保证后续映射可用
      await Promise.all([
        carClassifylist().then((response) => {
          this.classifyList = response.data.records;
        }),
        list().then((response) => {
          this.driverlist = response.rows;
        }),
      ]);

      this.open = true;

      if (row) {
        this.editId = row.id;
        this.title = "修改车辆";

        // 深拷贝一份数据到表单，切断与表格行的引用关系
        this.form = JSON.parse(JSON.stringify(row));

        // 如果有 driverId，则映射为 driverName（安全检查）
        if (this.driverlist && this.driverlist.length > 0 && this.form.driverId != null) {
          const driver = this.driverlist.find(
            (item) => item.id === parseInt(this.form.driverId)
          );
          if (driver) this.form.driverName = driver.name;
        }

        // 如果有 classify，则映射为 classifyName
        if (this.classifyList && this.classifyList.length > 0 && this.form.classify != null) {
          const cls = this.classifyList.find((item) => item.id === this.form.classify || item.id === parseInt(this.form.classify));
          if (cls) this.form.classifyName = cls.className;
        }
      } else {
        this.editId = null;
        this.form = {
          carNumber: "",
          name: "",
          classify: "",
          classifyName: "",
          licencePlate: "",
          imageUrl: "",
          driverPhone: "",
          deptId: "",
          status: "0",
          driverName: "",
          driverId: "",
          isCamera: 0, // 新增时默认不存在摄像头
        };
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      const deptId = store.getters.deptId;
      deptChildTreeSelect(deptId).then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.form.deptId = data.deptId;
      this.form.deptName = data.deptName;
    },
    //冻结状态
    handleFrost(row) {
      let rowstatus = 0;
      if (row.status === "0") {
        rowstatus = 1;
      }
      changeStatus({ id: row.id, status: rowstatus }).then((response) => {
        if (response.code === 200) {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }
      });
    },
    submit() {
      this.form.driverId = this.driverlist.find(
        (item) => item.name === this.form.driverName
      ).id;
      this.form.classify = this.classifyList.find(
        (item) => item.className === this.form.classifyName
      ).id;
      if (this.editId) {
        this.form.id = this.editId;
        editCar(this.form).then((response) => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addCar(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    beforeAvatarUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }
      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.form.imageUrl = res.data;
        this.$modal.closeLoading();
      } else {
        this.$modal.msgError(`上传图片出错`);
      }
    },
    handleDelete(ids) {
      delCar(ids).then((response) => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.manage-add-btn {
  float: right;
}

.uploadimage {
  width: 120px;
  height: 120px;
}
</style>
